<style lang="less">
  @import '../styles/common.less';
  @import '../tables/components/table.less';
</style>

<template>
  <div>
    <Row :gutter="10">
      <Card>
        <div class="table-head">
          <Button type="primary" class="Button" @click="remove()">删除</Button>
          <Button type="primary" class="Button" @click="add()">添加</Button>
        </div>
        <Row class="margin-top-10">
          <Table stripe border :columns="columns" :data="data" @on-row-click="onRowData"
                 @on-selection-change="selectionChange"></Table>
        </Row>
        <div style="margin: 10px;overflow: hidden;height: 36px;">
          <div style="float: right;">
            <Page :total="total" :current="page" @on-change="changePage" show-elevator></Page>
          </div>
        </div>
      </Card>
      <!--详情-->
      <Modal v-model="showCurrentTableData" :width="600" :mask-closable="false" :closable="false"
             class-name="vertical-center-modal" class="Modal-Detail-div">
        <h3 slot="header" style="color:#2D8CF0">详情</h3>
        <Form label-position="top">
          <FormItem label="组名">
            <div class="dataDetail-div" v-text="dataDetail.name"></div>
          </FormItem>
          <FormItem label="权限">
            <div class="dataDetail-div">
              <Tag color="geekblue" v-for="(el,index) in dataDetail.permission" :key="'permission' + index"
                   v-text="el.permission_name"></Tag>
            </div>
          </FormItem>
          <FormItem label="用户">
            <div class="dataDetail-div">
              <Tag color="default" v-for="(el,index) in dataDetail.user" :key="'user' + index"
                   v-if="delUserModal == false && addUserModal == false"
                   v-text="el.name"></Tag>
              <Tag color="primary" type="border" v-for="(el,index) in dataDetail.user" :key="'border' + index"
                   :name="el.id"
                   v-if="delUserModal == true"
                   closable @on-close="handleClose">{{el.name}}
              </Tag>
              <Tree v-if="addUserModal == true" ref="user_tree" :data="updateTreeData" show-checkbox
                    multiple></Tree>
            </div>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="asyncOK">取消</Button>
          <Button type="primary" @click="addUser"
                  v-if="addUserModal == false && delUserModal == false">添加用户
          </Button>
          <Button type="primary" @click="delUser"
                  v-if="delUserModal == false && addUserModal == false">删除用户
          </Button>
          <Button type="primary" @click="UserSave" v-if="delUserModal == true || addUserModal == true">确定</Button>
        </div>
      </Modal>
      <!--创建组-->
      <Modal v-model="addCurrentTableData" :width="600" :mask-closable="false" :closable="false"
             class-name="vertical-center-modal" class="Modal-Detail-div">
        <h3 slot="header" style="color:#2D8CF0">创建组</h3>
        <Form label-position="top">
          <FormItem label="组名">
            <Input v-model="addData.name" placeholder="组名"></Input>
          </FormItem>
          <FormItem label="权限">
            <div class="dataDetail-div Transfer">
              <Transfer
                  :data="TransferData"
                  :target-keys="targetKeysData"
                  filterable
                  :filter-method="filterMethod"
                  @on-change="TransferHandleChange"></Transfer>
            </div>
          </FormItem>
          <FormItem label="用户">
            <div class="dataDetail-div">
              <Tree ref="user_tree" :data="TreeData" show-checkbox multiple></Tree>
            </div>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="hideAddModal">取消</Button>
          <Button type="primary" :loading="saveLoading" @click="save()">确定</Button>
        </div>
      </Modal>
      <!--修改组权限-->
      <Modal v-model="updatePermissionModal" :width="600" :mask-closable="false" :closable="false"
             class-name="vertical-center-modal" class="Modal-Detail-div">
        <h3 slot="header" style="color:#2D8CF0">修改组权限</h3>
        <Form label-position="top">
          <FormItem label="组名">
            <Input v-model="addData.name" placeholder="组名"></Input>
          </FormItem>
          <FormItem label="权限">
            <div class="dataDetail-div Transfer">
              <Transfer
                  :data="TransferData"
                  :target-keys="targetKeysData"
                  filterable
                  :filter-method="filterMethod"
                  @on-change="TransferHandleChange"></Transfer>
            </div>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="hidePermissionModal">取消</Button>
          <Button type="primary" :loading="saveLoading" @click="savePermission()">确定</Button>
        </div>
      </Modal>
    </Row>
  </div>
</template>

<script>
  import Cookies from 'js-cookie';
  import Util from '../../libs/util';
  import Utils from '../../libs/mod.utils';
  import String from '../../libs/mod.string';
  import Modal from '../../libs/mod.Modal';
  export default {
    components: {},
    data () {
      return {
        total: 0,
        page: 1,
        size: 10,
        id: '',
        show_users: '',
        searchConName: '',
        searchConTel: '',
        showCurrentTableData: false,
        loading: true,
        showCurrentColumns: [],
        editInlineAndCellData: [],
        columns: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            key: 'name',
            title: '组名',
            width: 120,
          },
          {
            key: 'permission',
            title: '权限',
            render: (h, params) => {
              var permission = params.row.permission;
              var str = '';
              if (Utils.isArrayFn(permission) && permission.length > 0) {
                var arr = [];
                for (var i = 0; i < 3; i++) {
                  if (permission[i]) {
                    arr.push(permission[i].name);
                  }
                }
                str = arr.join('，');
                if (permission.length > 3) {
                  str += ' ......';
                }
              }
              return h('div', [
                h('span', str)
              ]);
            }
          },
          {
            key: 'user_num',
            title: '用户人数',
            width: 100,
          },
          {
            title: 'Action',
            key: 'action',
            width: 150,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: e => {
                      e.stopPropagation();
                      var data = params.row;
                      this.update(data, 'permission');
                    }
                  }
                }, '修改权限')
              ]);
            }
          }
        ],
        data: [],
        dataDetail: {},
        initTable: [],
        addCurrentTableData: false,
        updatePermissionModal: false,
        updateUserModal: false,
        saveLoading: false,
        ajaxType: 'add',
        addData: {
          name: '',
        },
        selectionArr: [],
        RolesArr: [],
        TreeData: [],
        updateTreeData: [],
        checked_dep_arr: [],
        checked_users_arr: [],
        TransferData: [],
        targetKeysData: [],
        delUserModal: false,
        addUserModal: false,
      };
    },
    mounted () {
      this.getData();
      this.getRolesArr();
    },
    methods: {
      getData () {
        var _this = this;
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          page: _this.page,
          size: _this.size,
        };
        var params = {
          url: '/roles/list',
          //domain: 'http://sd.jnaw.top/sd2-mock',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.total = res.rows;
            _this.data = _data;
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      handleSearch () {
        var _this = this;
        _this.page = 1;
        var searchConName = _this.searchConName;
      },
      changePage (page) {
        var _this = this;
        _this.page = page;
        _this.getData();
      },
      onRowData: function (data, index) {
        var _this = this;
        _this.show(data);
      },
      show: function (data) {
        var _this = this;
        var id = data.id;
        _this.id = id;

        var data = {
          id: _this.id,
        };
        var params = {
          url: '/roles/query',
          //domain: 'http://sd.jnaw.top/sd2-mock',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.dataDetail = _data;
            _this.showCurrentTableData = true;
            _this.delUserModal = false;
            _this.addUserModal = false;
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      asyncOK: function () {
        var _this = this;
        _this.showCurrentTableData = false;
        _this.delUserModal = false;
        _this.addUserModal = false;
      },
      // 穿梭框搜索
      filterMethod (data, query) {
        return data.label.indexOf(query) > -1;
      },
      // 穿梭框回调
      TransferHandleChange: function (newTargetKeys) {
        var _this = this;
        _this.targetKeysData = newTargetKeys;
      },
      // 删除用户
      handleClose: function (event, name) {
        var _this = this;
        var id = name;
        var user = _this.dataDetail.user;
        for (var k in user) {
          if (!user[k]) {
            continue;
          }
          if (id == user[k].id) {
            user.splice(k, 1);
            break;
          }
        }
        _this.dataDetail.user = user;
      },
      // 获取权限
      getRolesArr: function () {
        var _this = this;
        var data = {};
        var params = {
          url: '/roles/permission/list',
          //domain: 'http://sd.jnaw.top/sd2-mock',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.RolesArr = _data;
            var TransferData = [];
            for (var k in _data) {
              if (!_data[k]) {
                continue;
              }
              var obj = {
                key: _data[k].id,
                label: _data[k].permission_name
              };
              TransferData.push(obj);
            }
            _this.TransferData = TransferData;
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      // 获取选人 树信息
      getTreeData: function () {
        var _this = this;
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          id: 1
        };
        var params = {
          url: '/department/query',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var data = res.data || [];
            var TreeData = [];
            TreeData.push(data);
            _this.toDataFun(TreeData);
            _this.TreeData = TreeData;
            _this.updateTreeData = Utils.cloneObj(TreeData);
          } else {
            _this.$Message.error('查询人员信息失败!');
          }
        }
      },
      // 处理树信息
      toDataFun: function (arr) {
        var _this = this;
        arr.forEach(function (e) {
          e.title = e.name;
          e.expand = true;//展开
          if (e.type) {
            e.type = 'dep';
            var checked_dep_arr = _this.checked_dep_arr;
            if (Utils.idInArray(e.id, checked_dep_arr)) {
              e.checked = true;// 选中
            }
          } else {
            e.type = 'user';
            var checked_users_arr = _this.checked_users_arr;
            if (Utils.idInArray(e.id, checked_users_arr)) {
              e.checked = true;// 选中
            }
          }
          var staff = e.staff || [];
          var children = e.children || [];
          if (children.length == 0) {
            e.children = [];
          }
          e.children.push(...staff);
          _this.toDataFun(e.children);
        });
      },
      // 列表多选 选中数据
      selectionChange: function (selection) {
        var _this = this;
        _this.selectionArr = selection;
      },
      // 隐藏编辑页面
      hideAddModal: function () {
        var _this = this;
        _this.addCurrentTableData = false;
      },
      // 显示添加界面
      add: function () {
        var _this = this;
        _this.ajaxType = 'add';
        _this.addData.name = '';
        _this.targetKeysData = [];
        _this.TreeData = [];
        _this.updateTreeData = [];
        _this.checked_users_arr = [];
        _this.getTreeData();
        _this.addCurrentTableData = true;
      },
      // 保存数据
      save: function () {
        var _this = this;
        var name = _this.addData.name;
        var targetKeysData = _this.targetKeysData;
        var CheckedNodes = _this.$refs.user_tree.getCheckedNodes();
        if (!(name && name != '')) {
          _this.$Message.error('请输入组名!');
          return false;
        }
        if (targetKeysData.length == 0) {
          _this.$Message.error('请选择权限!');
          return false;
        }
        var departments = [];
        var users = [];
        for (var k in CheckedNodes) {
          if (!CheckedNodes[k]) {
            continue;
          }
          var id = CheckedNodes[k].id;
          var type = CheckedNodes[k].type;
          if (type == 'dep') {
            departments.push(id);
          } else if (type == 'user') {
            var username = CheckedNodes[k].username;
            users.push(username);
          }
        }
        /*if (users.length == 0) {
         _this.$Message.error('请选择人员!');
         return false;
         }*/
        users = Utils.onlyArray(users);
        var data = {
          id: _this.id,
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          name: name,
          user: users,
          permission: targetKeysData,
        };
        var params = {
          url: '/roles/add',
          //domain: 'http://sd.jnaw.top/sd2-mock',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.page = 1;
            _this.getData();
            _this.addData.name = '';
            _this.targetKeysData = [];

            _this.TreeData = [];
            _this.updateTreeData = [];
            _this.checked_users_arr = [];

            _this.addCurrentTableData = false;
          } else {
            _this.$Message.error('保存信息失败!');
          }
        }
      },
      // 显示修改权限界面
      update: function (data, type) {
        var _this = this;
        _this.ajaxType = 'update';
        var id = data.id;
        _this.id = id;
        var data = {
          id: _this.id,
        };
        var params = {
          url: '/roles/query',
          //domain: 'http://sd.jnaw.top/sd2-mock',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            var checked_users_arr = [];
            var targetKeysData = [];
            var id = _data.id;
            var name = _data.name;
            var permission = _data.permission;
            var users = _data.user;
            for (var k in permission) {
              if (!permission[k]) {
                continue;
              }
              targetKeysData.push(permission[k].id);
            }
            for (var k in users) {
              if (!users[k]) {
                continue;
              }
              checked_users_arr.push(users[k].id);
            }
            _this.checked_users_arr = checked_users_arr;
            _this.addData.name = name;
            _this.targetKeysData = targetKeysData;

            if (type == 'permission') {
              _this.updatePermissionModal = true;
            } else if (type == 'user') {
              _this.getTreeData();
              _this.updateUserModal = true;
            }

          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      hidePermissionModal: function () {
        var _this = this;
        _this.updatePermissionModal = false;
      },
      // 修改组权限
      savePermission: function () {
        var _this = this;
        var name = _this.addData.name;
        var targetKeysData = _this.targetKeysData;
        if (!(name && name != '')) {
          _this.$Message.error('请输入组名!');
          return false;
        }
        if (targetKeysData.length == 0) {
          _this.$Message.error('请选择权限!');
          return false;
        }
        var data = {
          id: _this.id,
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          name: name,
          permission: targetKeysData,
          action: 'permission',
        };
        var params = {
          url: '/roles/update',
          //domain: 'http://sd.jnaw.top/sd2-mock',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.getData();
            _this.addData.name = '';
            _this.targetKeysData = [];

            _this.TreeData = [];
            _this.updateTreeData = [];
            _this.checked_users_arr = [];

            _this.updatePermissionModal = false;
          } else {
            _this.$Message.error('保存信息失败!');
          }
        }
      },
      // 删除用户
      delUser: function () {
        var _this = this;
        _this.delUserModal = true;
        _this.addUserModal = false;
      },
      // 添加用户
      addUser: function () {
        var _this = this;
        _this.TreeData = [];
        _this.updateTreeData = [];
        _this.checked_users_arr = _this.dataDetail.user || [];
        _this.getTreeData();
        _this.delUserModal = false;
        _this.addUserModal = true;
      },
      UserSave: function () {
        var _this = this;
        var user = [];
        if (_this.delUserModal == true) {
          var userArr = _this.dataDetail.user;
          for (var k in userArr) {
            if (!userArr[k]) {
              continue;
            }
            var username = userArr[k].username;
            user.push(username);
          }
        } else if (_this.addUserModal == true) {
          var CheckedNodes = _this.$refs.user_tree.getCheckedNodes();
          var newUser = [];
          for (var k in CheckedNodes) {
            if (!CheckedNodes[k]) {
              continue;
            }
            var id = CheckedNodes[k].id;
            var type = CheckedNodes[k].type;
            if (type == 'user') {
              var username = CheckedNodes[k].username;
              newUser.push(username);
            }
          }
          var userArr = _this.dataDetail.user;
          var oldUser = [];
          for (var k in userArr) {
            if (!userArr[k]) {
              continue;
            }
            var username = userArr[k].username;
            oldUser.push(username);
          }
          user = Utils.mergeArray(newUser, oldUser);
        }
        user = Utils.onlyArray(user);
        var data = {
          id: _this.id,
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          user: user,
          action: 'user',
        };
        var params = {
          url: '/roles/update',
          //domain: 'http://sd.jnaw.top/sd2-mock',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.getData();
            var data = {
              id: _this.id
            };
            _this.show(data);

            _this.delUserModal = false;
            _this.addUserModal = false;
          } else {
            _this.$Message.error('保存信息失败!');
          }
        }
      },
      // 删除
      remove: function () {
        var _this = this;
        var selectionArr = _this.selectionArr;
        if (selectionArr.length == 0) {
          _this.$Message.error('请填选择要删除的数据!');
          return false;
        }
        var selectionIds = [];
        for (var k in selectionArr) {
          if (!selectionArr[k]) {
            continue;
          }
          var id = selectionArr[k].id;
          selectionIds.push(id);
        }
        Modal.confirm(_this, {content: '确定删除选中的信息？'}, function () {
          var data = {
            id: selectionIds,
          };
          var params = {
            url: '/roles/delete',
            type: Util.method.get,
            data: data,
            success: _successFun
          };
          Util.ajax(_this, params);
          function _successFun(res) {
            if (res.result == 0) {
              _this.page = 1;
              _this.getData();
            } else {
              _this.$Message.error('删除信息失败!');
            }
          }
        }, function () {
        });
      },

    }
  };
</script>
